package com.sanguo.servlet;

import com.sanguo.dao.GeneralDAO;
import com.sanguo.entity.General;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/general")
public class GeneralServlet extends HttpServlet {
    private GeneralDAO generalDAO = new GeneralDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        String action = request.getParameter("action");
        if (action == null) {
            action = "list";
        }

        switch (action) {
            case "list":
                listGenerals(request, response);
                break;
            case "add":
                showAddForm(request, response);
                break;
            case "edit":
                showEditForm(request, response);
                break;
            case "delete":
                deleteGeneral(request, response);
                break;
            default:
                listGenerals(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        String action = request.getParameter("action");
        if (action == null) {
            action = "list";
        }

        switch (action) {
            case "save":
                saveGeneral(request, response);
                break;
            default:
                listGenerals(request, response);
        }
    }

    private void listGenerals(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取分页参数
        int page = 1;
        int pageSize = 5;
        String pageStr = request.getParameter("page");
        String pageSizeStr = request.getParameter("pageSize");
        
        if (pageStr != null && !pageStr.isEmpty()) {
            page = Integer.parseInt(pageStr);
        }
        if (pageSizeStr != null && !pageSizeStr.isEmpty()) {
            pageSize = Integer.parseInt(pageSizeStr);
        }

        // 获取排序参数
        String sortField = request.getParameter("sort");
        if (sortField == null) {
            sortField = "id";
        }

        // 获取总记录数
        int totalRecords = generalDAO.getTotalGenerals();
        int totalPages = (int) Math.ceil((double) totalRecords / pageSize);

        // 获取当前页的武将列表
        List<General> generals = generalDAO.getGenerals(page, pageSize, sortField);

        // 设置请求属性
        request.setAttribute("generals", generals);
        request.setAttribute("currentPage", page);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("sortField", sortField);
        request.setAttribute("pageSize", pageSize);

        // 转发到列表页面
        request.getRequestDispatcher("/generalList.jsp").forward(request, response);
    }

    private void showAddForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/generalForm.jsp").forward(request, response);
    }

    private void showEditForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        General general = generalDAO.getGeneralById(id);
        request.setAttribute("general", general);
        request.getRequestDispatcher("/generalForm.jsp").forward(request, response);
    }

    private void saveGeneral(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String idStr = request.getParameter("id");
            String name = request.getParameter("name");
            int strategy = Integer.parseInt(request.getParameter("strategy"));
            int force = Integer.parseInt(request.getParameter("force"));
            int agility = Integer.parseInt(request.getParameter("agility"));

            General general = new General();
            general.setName(name);
            general.setStrategy(strategy);
            general.setForce(force);
            general.setAgility(agility);

            if (idStr != null && !idStr.isEmpty()) {
                // 更新现有武将
                general.setId(Integer.parseInt(idStr));
                generalDAO.updateGeneral(general);
            } else {
                // 添加新武将
                generalDAO.addGeneral(general);
            }

            response.sendRedirect("general?action=list");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "保存失败：" + e.getMessage());
            request.getRequestDispatcher("/generalForm.jsp").forward(request, response);
        }
    }

    private void deleteGeneral(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        generalDAO.deleteGeneral(id);
        response.sendRedirect("general?action=list");
    }
} 